'''
Author: 13896370136 3361098@qq.com
Date: 2024-03-11 13:14:56
LastEditors: 13896370136 3361098@qq.com
LastEditTime: 2024-03-14 14:11:24
FilePath: \ShopExport\app.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
# -*- coding: UTF-8 -*-
import sys, os
import threading
# import queue
from PySide6.QtGui import *
from PySide6.QtCore import Qt
from PySide6.QtGui import QPaintEvent
from PySide6.QtWidgets import *
from mainUi import Ui_Dialog, has_password, has_place,icon
from yinxindb import out_yinxin
from yaodb import out_yao
from huo import out_huo_login, out_huo_data


# nowPlace = queue.Queue()

class MainWindow(QWidget, Ui_Dialog):
    def __init__(self):
        QWidget.__init__(self)
        Ui_Dialog.__init__(self)
        self.setupUi(self)
        self.resize(400, 300)
        # 预定义变量
        self.ask = has_password()
        self.pid = has_place()
        # 窗口标记
        self.m_flag = False
        self.__set_up_ui()
    def __set_up_ui(self):
        self.setWindowTitle("YaoDB")
        self.setWindowIcon(QIcon(":icon/logo.png"))
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(
            Qt.FramelessWindowHint
            | Qt.Window
            | Qt.WindowType.FramelessWindowHint
            # | QtCore.Qt.WindowStaysOnBottomHint
        )
        # 数据
        data = [[":icon/yinxin.png","银杏网咖运营"],[":icon/yao2.png","小妖2"],[":icon/huo.png","火星捕手"]]
        self.fdb.load(data)
        # 信号槽
        self.toolbar.actionTriggered.connect(self.MSG_SYSTEM)
        self.fdb.currentTextChanged.connect(self.MSG_FDB)
        self.fbt.clicked.connect(self.MSG_FBT)
        self.tbt.clicked.connect(self.MSG_TBT)
        self.log.finished.connect(self.MSG_LOG)
        self.ask.submit.clicked.connect(lambda: self.MSG_ASK(self.ask.username.text(),self.ask.password.text()))
        self.pid.toolbar.actionTriggered.connect(self.MSG_PID)
        # css
        self.setStyleSheet("""
        MainWindow {background-color: qlineargradient(spread:pad, x1:1, y1:1, x2:0, y2:0, stop:0 rgba(14,70,200, 255), stop:1 rgba(255, 255, 255, 255)); border-radius: 5px;}        
        """)
    def MSG_PID(self, e):
        # print(e.data())
        # nowPlace.put(e.data())
        self.pid.done(0)
        self.log.info("[火星捕手] 准备导出商品数据.")
        self.fbt.setEnabled(False)
        self.tbt.setEnabled(False)        
        is_Run = threading.Thread(target=out_huo_data, args=(e.data(),self.log))
        is_Run.start()
    def MSG_ASK(self, u, p):
        # print(u, p) 
        if not u or not p:
            QMessageBox.warning(self.ask, "警告", "用户名或密码不能为空")
        else:    
            self.ask.done(0) 
            self.log.info("[火星捕手] 准备导出商品数据.")
            self.fbt.setEnabled(False)
            self.tbt.setEnabled(False)
            is_Run = threading.Thread(target=out_huo_login, args=(u,p,self.log))
            is_Run.start()             
    def MSG_LOG(self, e=0):
        self.fbt.setEnabled(True)
        self.tbt.setEnabled(True)
        if e == 2:
            self.pid.setData(self.log.place)
            self.pid.show()
        # print("完成")
    def MSG_TBT(self):
        """浏览结果"""
        x = self.log.file
        # print("浏览",x)
        if x:
            self.log.info(f'打开文件: {x}')
            os.system(f"start {x}")
    def MSG_FBT(self):
        """开始导出"""
        self.tbt.setEnabled(False)
        if self.fdb.currentText() == "银杏网咖运营":
            self.log.info("[银杏] 准备导出商品数据.")
            self.fbt.setEnabled(False)
            self.tbt.setEnabled(False)
            is_Run = threading.Thread(target=out_yinxin, args=(self.log,))
            is_Run.start()
        if self.fdb.currentText() == "小妖2":
            self.log.info("[小妖2] 准备导出商品数据.")
            self.fbt.setEnabled(False)
            self.tbt.setEnabled(False)
            is_Run = threading.Thread(target=out_yao, args=(self.log,))
            is_Run.start()          
        if self.fdb.currentText() == "火星捕手":
            self.ask.show() 
            # self.log.info("[火星捕手] 准备导出商品数据.")
            # self.fbt.setEnabled(False)
            # self.tbt.setEnabled(False)
            # is_Run = threading.Thread(target=out_huo, args=(self.log,))
            # is_Run.start() 
    def MSG_FDB(self, e):
        """FDB消息"""
        pass
    def MSG_SYSTEM(self, e):
        """系统工具栏消息"""
        if e.text() == "最小化":
            self.showMinimized()
        if e.text() == "最大化":
            if self.isMaximized():
                self.showNormal()
                e.setIcon(
                    QApplication.style().standardIcon(
                        QStyle.SP_TitleBarMaxButton
                    )
                )
            else:
                self.showMaximized()
                e.setIcon(
                    QApplication.style().standardIcon(
                        QStyle.SP_TitleBarNormalButton
                    )
                )
        if e.text() == "关闭":
            self.close()
    def mousePressEvent(self, QMouseEvent):
        if QMouseEvent.button() == Qt.LeftButton:
            if self.isMaximized():
                return
            pos = QMouseEvent.globalPosition().toPoint()
            self.m_flag = True
            self.m_Position = pos - self.pos()  # 获取鼠标相对窗口的位置
            QMouseEvent.accept()
            self.setCursor(QCursor(Qt.OpenHandCursor))  # 更改鼠标图标

    def mouseMoveEvent(self, QMouseEvent):
        if QMouseEvent.buttons() == Qt.LeftButton and self.m_flag:
            if self.isMaximized():
                self.showNormal()
            pos = QMouseEvent.globalPosition().toPoint()
            self.move(pos - self.m_Position)  # 更改窗口位置
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QCursor(Qt.ArrowCursor))

    def paintEvent(self, event: QPaintEvent) -> None:
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)
        return super().paintEvent(event)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec())